package com.zige.zige.data;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;

import com.zige.zige.utils.StringUtils;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class ImageLoaderTask extends AsyncTask<String, Void, Bitmap> {
	private final WeakReference<ImageView> imageViewReference; // 防止内存溢出

	public ImageLoaderTask(ImageView imageView) {
		imageViewReference = new WeakReference<ImageView>(imageView);
	}
	@Override
	protected Bitmap doInBackground(String... params) {
		
		return loadImageFile(params[0]);
	}

	
	private Bitmap loadImageFile(final String filename ) {
		InputStream is = null;
		try {
			
//			URL url = new URL(filename);
//			URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
//			url = uri.toURL();
			StringBuffer url = new StringBuffer();
			for(int i = 0; i<filename.length(); i++){
				char c = filename.charAt(i);
				if(StringUtils.isChinese(c))
					url.append(URLEncoder.encode(String.valueOf(c),"utf-8"));
				else
					url.append(String.valueOf(c));
			}
			Bitmap bmp = BitmapCache.getInstance().getBitmap(url.toString().replaceAll(" ", "%20"));
			return bmp;
		} catch (Exception e) {
			Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@Override
	protected void onPostExecute(Bitmap bitmap) {
		if (isCancelled()) {
			bitmap = null;
		}

		if (imageViewReference != null) {
			ImageView imageView = imageViewReference.get();
			if (imageView != null) {
				if (bitmap != null) {
//					imageView.setBackgroundDrawable(new BitmapDrawable(bitmap));;
					imageView.setImageBitmap(bitmap);
				}

			}
		}
	}


}